<template>
  <div class="student-exams">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>考试管理</span>
          <el-button type="primary" @click="handleAdd">新增考试</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="考试科目">
          <el-select v-model="searchForm.subject" placeholder="选择科目" clearable>
            <el-option label="科目一" value="subject1" />
            <el-option label="科目二" value="subject2" />
            <el-option label="科目三" value="subject3" />
            <el-option label="科目四" value="subject4" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="考试结果">
          <el-select v-model="searchForm.result" placeholder="选择结果" clearable>
            <el-option label="通过" value="pass" />
            <el-option label="未通过" value="fail" />
            <el-option label="待考" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="学员姓名/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 考试列表 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="studentName" label="学员姓名" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="subject" label="考试科目" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.subject }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="examDate" label="考试日期" width="120" />
        <el-table-column prop="examTime" label="考试时间" width="120" />
        <el-table-column prop="examLocation" label="考试地点" min-width="200" show-overflow-tooltip />
        <el-table-column prop="score" label="考试成绩" width="100">
          <template #default="{ row }">
            <span v-if="row.status === 'completed'">{{ row.score }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="考试状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="考试结果" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'completed'" :type="row.result === 'pass' ? 'success' : 'danger'">
              {{ row.result === 'pass' ? '通过' : '未通过' }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handleEdit(row)"
            >编辑</el-button>
            <el-button
              v-if="row.status === 'completed'"
              type="primary"
              link
              @click="handleView(row)"
            >查看</el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              link
              @click="handleCancel(row)"
            >取消</el-button>
            <el-button
              v-if="row.status === 'in_progress'"
              type="success"
              link
              @click="handleRecord(row)"
            >录入成绩</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑考试抽屉 -->
      <el-drawer
        :title="dialogType === 'add' ? '新增考试' : '编辑考试'"
        v-model="drawerVisible"
        direction="rtl"
        size="600px"
        custom-class="exam-drawer"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="考试科目" prop="subject">
            <el-select v-model="form.subject" placeholder="选择科目">
              <el-option label="科目一" value="subject1" />
              <el-option label="科目二" value="subject2" />
              <el-option label="科目三" value="subject3" />
              <el-option label="科目四" value="subject4" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试日期" prop="examDate">
            <el-date-picker
              v-model="form.examDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="考试时间" prop="examTime">
            <el-time-select
              v-model="form.examTime"
              start="08:30"
              step="00:30"
              end="17:30"
              placeholder="选择时间"
            />
          </el-form-item>
          <el-form-item label="考试地点" prop="examLocation">
            <el-input v-model="form.examLocation" placeholder="请输入考试地点" />
          </el-form-item>
          <el-form-item label="学员" prop="studentId">
            <el-select
              v-model="form.studentId"
              placeholder="选择学员"
              filterable
              remote
              :remote-method="searchStudents"
              :loading="studentLoading"
            >
              <el-option
                v-for="student in students"
                :key="student.id"
                :label="student.name"
                :value="student.id"
              >
                <span>{{ student.name }}</span>
                <span class="student-info">{{ student.phone }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-drawer>

      <!-- 成绩录入抽屉 -->
      <el-drawer
        title="成绩录入"
        v-model="recordDrawerVisible"
        direction="rtl"
        size="500px"
        custom-class="score-drawer">
        <el-form
          ref="recordFormRef"
          :model="recordForm"
          :rules="recordRules"
          label-width="100px"
        >
          <el-form-item label="考试成绩" prop="score">
            <el-input-number
              v-model="recordForm.score"
              :min="0"
              :max="100"
              :precision="0"
              :step="1"
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="考试结果" prop="result">
            <el-radio-group v-model="recordForm.result">
              <el-radio label="pass">通过</el-radio>
              <el-radio label="fail">未通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="recordForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="recordDrawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleRecordSubmit">确定</el-button>
          </span>
        </template>
      </el-drawer>

      <!-- 考试详情抽屉 -->
      <el-drawer
        title="考试详情"
        v-model="detailDrawerVisible"
        direction="rtl"
        size="600px"
        custom-class="detail-drawer">
        <div class="detail-container">
          <div class="detail-item">
            <span class="detail-label">学员姓名:</span>
            <span class="detail-value">{{ detailForm.studentName }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">联系电话:</span>
            <span class="detail-value">{{ detailForm.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试科目:</span>
            <span class="detail-value">{{ detailForm.subject }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试日期:</span>
            <span class="detail-value">{{ detailForm.examDate }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试时间:</span>
            <span class="detail-value">{{ detailForm.examTime }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试地点:</span>
            <span class="detail-value">{{ detailForm.examLocation }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试成绩:</span>
            <span class="detail-value">{{ detailForm.score }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试状态:</span>
            <span class="detail-value">
              <el-tag :type="getStatusType(detailForm.status)">
                {{ getStatusText(detailForm.status) }}
              </el-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">考试结果:</span>
            <span class="detail-value">
              <el-tag v-if="detailForm.status === 'completed'" :type="detailForm.result === 'pass' ? 'success' : 'danger'">
                {{ detailForm.result === 'pass' ? '通过' : '未通过' }}
              </el-tag>
              <span v-else>-</span>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">备注:</span>
            <span class="detail-value">{{ detailForm.remark || '无' }}</span>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDrawerVisible = false">关闭</el-button>
          </span>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = ref({
  subject: '',
  dateRange: [],
  result: '',
  keyword: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    id: '1',
    studentName: '张三',
    phone: '13800138000',
    subject: '科目二',
    examDate: '2024-03-15',
    examTime: '09:00',
    examLocation: '市交通大队考场',
    score: 92,
    status: 'completed',
    result: 'pass'
  },
  {
    id: '2',
    studentName: '李四',
    phone: '13800138001',
    subject: '科目二',
    examDate: '2024-03-20',
    examTime: '14:00',
    examLocation: '市交通大队考场',
    status: 'pending'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const drawerVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  subject: '',
  examDate: '',
  examTime: '',
  examLocation: '',
  studentId: '',
  remark: ''
})

// 表单验证规则
const rules = {
  subject: [{ required: true, message: '请选择考试科目', trigger: 'change' }],
  examDate: [{ required: true, message: '请选择考试日期', trigger: 'change' }],
  examTime: [{ required: true, message: '请选择考试时间', trigger: 'change' }],
  examLocation: [{ required: true, message: '请输入考试地点', trigger: 'blur' }],
  studentId: [{ required: true, message: '请选择学员', trigger: 'change' }]
}

// 成绩录入对话框
const recordDrawerVisible = ref(false)
const recordFormRef = ref(null)
const recordForm = ref({
  score: 0,
  result: 'pass',
  remark: ''
})

// 成绩录入表单验证规则
const recordRules = {
  score: [{ required: true, message: '请输入考试成绩', trigger: 'blur' }],
  result: [{ required: true, message: '请选择考试结果', trigger: 'change' }]
}

// 学员选择
const students = ref([])
const studentLoading = ref(false)

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'in_progress': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return typeMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待考',
    'in_progress': '考试中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 搜索学员
const searchStudents = (query) => {
  if (query) {
    studentLoading.value = true
    // 模拟搜索
    setTimeout(() => {
      students.value = [
        { id: '1', name: '张三', phone: '13800138000' },
        { id: '2', name: '李四', phone: '13800138001' }
      ]
      studentLoading.value = false
    }, 500)
  } else {
    students.value = []
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    subject: '',
    dateRange: [],
    result: '',
    keyword: ''
  }
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    subject: '',
    examDate: '',
    examTime: '',
    examLocation: '',
    studentId: '',
    remark: ''
  }
  drawerVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

import { useRouter } from 'vue-router'

const router = useRouter()

// 查看详情抽屉
const detailDrawerVisible = ref(false)
const detailForm = ref({})

// 查看
const handleView = (row) => {
  if (!row?.id) {
    ElMessage.error('无效的考试记录')
    return
  }
  // 模拟获取详情数据
  detailForm.value = { ...row }
  detailDrawerVisible.value = true
}

// 取消考试
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认取消该考试吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现取消逻辑
    ElMessage.success('考试已取消')
  }).catch(() => {})
}

// 录入成绩
const handleRecord = (row) => {
  recordForm.value = {
    score: 0,
    result: 'pass',
    remark: ''
  }
  recordDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 实现提交逻辑
      ElMessage.success(dialogType.value === 'add' ? '考试添加成功' : '考试修改成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 提交成绩
const handleRecordSubmit = async () => {
  if (!recordFormRef.value) return
  await recordFormRef.value.validate((valid) => {
    if (valid) {
      // 实现提交逻辑
      ElMessage.success('成绩录入成功')
      recordDialogVisible.value = false
      fetchData()
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    total.value = tableData.value.length
    loading.value = false
  }, 500)
}
</script>

<style scoped>
.student-exams {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-container {
  padding: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.student-info {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
</style>